package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.IUserDao;
import com.cn.wanxi.dao.impl.UserImpl;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;

import java.util.List;

public class UserServiceImpl implements IUserService {
    @Override
    public int add(UserModel userModel) {
        IUserDao iUserDao = new UserImpl();
//首先拿到当前用户名去查询数据库，如果存在则提示用户名存在，
// 返回true，否则返回false，表示不存在，则可以进行插入

        int count = 0;
        if (findByUsername(userModel.getUsername())) {
            count = -1;
        } else {
            count = iUserDao.add(userModel);
        }
        return count;
    }

    @Override
    public int login(UserModel userModel) {
        int result = 0;
//        1.判断验证码是否正确
        if (userModel.getCode().equals(userModel.getSessionCode())) {
            //        2.判断用户是否存在（用户和密码）
            if (findByUsernameAndPassword(userModel)) {
                result = 1;
            }
        } else {
            result = -1;
        }
        return result;

    }

    @Override
    public List<UserModel> findAll(UserModel userModel) {
        IUserDao iUserDao = new UserImpl();
        return iUserDao.findAll(userModel);
    }

    @Override
    public int del(int id) {
        IUserDao iUserDao = new UserImpl();
        return iUserDao.del(id);
    }

    @Override
    public UserModel findById(int id) {
        IUserDao iUserDao = new UserImpl();
        return iUserDao.findById(id);
    }

    @Override
    public int edit(UserModel userModel) {
        IUserDao iUserDao = new UserImpl();
        return iUserDao.edit(userModel);
    }

    @Override
    public int getCount(UserModel userModel) {
        IUserDao iUserDao = new UserImpl();
        return iUserDao.getCount(userModel);
    }

    /**
     * 根据用户名和密码去数据库查询，如果有则返回true，否则返回false；
     *
     * @param userModel
     * @return
     */
    private boolean findByUsernameAndPassword(UserModel userModel) {
        IUserDao iUserDao = new UserImpl();
        return iUserDao.findByUsernameAndPassword(userModel);
    }

    private boolean findByUsername(String username) {
        IUserDao iUserDao = new UserImpl();
        return iUserDao.findByUsername(username);
    }
}
